package com.zhu.netty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.http.*;
import io.netty.util.AsciiString;

import java.util.List;
import java.util.Map;

/**
 * Created by ehsy_it on 2016-05-09.
 */
public class StringToHttpResponseOutboundHandler extends MessageToMessageEncoder<String> {
    private static final AsciiString CONTENT_TYPE = new AsciiString("Content-Type");
    private static final AsciiString CONTENT_LENGTH = new AsciiString("Content-Length");
    private static final AsciiString CONNECTION = new AsciiString("Connection");
    private static final AsciiString KEEP_ALIVE = new AsciiString("keep-alive");

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, String s, List<Object> list) throws Exception {
        if (s != null) {
            ByteBuf buf = Unpooled.copiedBuffer(s.getBytes());

            FullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
            resp.headers().add(CONTENT_TYPE, "text/plain");
            resp.headers().add(CONTENT_LENGTH, resp.content().readableBytes());

            list.add(resp);
        }
    }
}



